package LUCKY.Android;


import LUCKY.Android.DataAccess.EJEMPLARTABLE;
import LUCKY.Android.Util.FunctionsUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class actListanimales  extends ListActivityLUCKY {
	protected static final String CLASS_NAME = "actListAvisos";
	private Activity m_activity;
	private ListView empListView;
	protected final int SECONDARY_ACTIVITY_REQUEST_CODE=0;
	//private static final Logger logger = LoggerFactory.getLogger();
	
	enum MODOLista {AVISOS, AVISOS_NUEVOS};
	private static String Selec_Cliente_Zona_Centro_ID = "";
	protected MODOLista modoLista;
	int contadoravisos = 0;
	EJEMPLARTABLE avisosTable = new EJEMPLARTABLE(this);
	Cursor c;
	protected static String queryconfiltro = "";
	protected SimpleCursorAdapter adapter2;
	private int position=0;
	String activityoringn = "";
	@Override
	protected void onDestroy() {
		super.onDestroy();
	 
		if (c!=null) c.close();
		if (avisosTable!=null) avisosTable.close();
	}
	
	
	@Override
	protected void onPause() {
		super.onPause();
		valoresGenerales.actListanimales=null;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		valoresGenerales.actListanimales=this;
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        try
        {
        	super.onCreate(savedInstanceState);
        	//ExceptionHandler.register(this, valoresGenerales.STACKTRACE_URL); 
        	valoresGenerales.actListanimales=this;
        	m_activity = actListanimales.this;
        	
        	avisosTable.open();
        	
        	
        	
            
           
                LoadLista();
                //OBTENER LOS AVISOS HACIA LA DB DE ANDROID
                //InitCheckNewMaintenances();
               
            	position = getIntent().getIntExtra("position",0);
                
           
        	// se pone en 3 para que no se ejecute mientras esta en este activity
  		   valoresGenerales.sharedPrefs.edit().putString("id_desactivacion_filtro", "3").commit();
  		 estableceTitulos();
            
            
        }
        catch (Exception ex)
        {
            logger.debug(CLASS_NAME + " - onCreate");
            logger.debug(FunctionsUtil.getExceptionInfoToLog(ex));
            FunctionsUtil.ShowMessage("Error: " + ex.getMessage(),Toast.LENGTH_LONG);
        }
    }
	
	protected Cursor preparaCursor() {
		Cursor c = null;

		
				c = avisosTable.fetchAll2();
			
			return c;
		
	}
	
	protected void estableceTitulos() {
		
		String valor = valoresGenerales.sharedPrefs.getString("SelectedClienteZonaCentro_ID", "");
		
		if (!valor.equals(""))
		{
			if (modoLista==MODOLista.AVISOS)
				setTitle("Lista de "+ contadoravisos +" Avisos Con Filtro");
			else if (modoLista==MODOLista.AVISOS_NUEVOS)
				setTitle("Lista de "+ contadoravisos +" Avisos Nuevos Con Filtro");
		}
		else
		{
			if (modoLista==MODOLista.AVISOS)
				setTitle("Lista de "+ contadoravisos +" Avisos");
			else if (modoLista==MODOLista.AVISOS_NUEVOS)
				setTitle("Lista de "+ contadoravisos +" Avisos Nuevos");
			
		}
		
		
	}
	
	protected void LoadLista()
    {
        ProgressDialog progressDialog = ProgressDialog.show(actListanimales.this, "Buscando", "Por favor espere...", true);
        try
        {
            String msg = "";
            if (c!=null) c.close();
            c = preparaCursor();
            	
            contadoravisos = c.getCount();
            if (c != null){
            	adapter2 = obtenAdaptador(c);
            	
           
            	empListView = (ListView)getListView();
            	ColorDrawable sage = new ColorDrawable(0xffffc800); // 0xffff0000 
            	empListView.setDivider(sage);
            	empListView.setDividerHeight(1);
            	//empListView.addHeaderView(header);
              	empListView.setAdapter(adapter2);
              	//HHA

               	empListView.setClickable(true);
              	empListView.setOnItemClickListener(new OnItemClickListener() {
              		@Override
              		public void onItemClick(AdapterView<?> a, View v, int position, long id) {
              			Cursor c=(Cursor)empListView.getItemAtPosition(position);
              			int idAviso = c.getInt(1); // 0: corresponde al campo _id
              			int _idAviso = c.getInt(0); // 0: corresponde al campo _id
              			/*Intent intent;
              			
              				 intent = new Intent(m_activity,actCrearAviso.class);
              			
              			
              			
              			int index=-1;
            			int top=-1;
            			if (empListView!=null) {
            				index = empListView.getFirstVisiblePosition();
            				View v2 = empListView.getChildAt(0);
            				top = (v2 == null) ? 0 : v2.getTop();
            			}
           
            			intent.putExtra("index", index);
              	    	intent.putExtra("top", top);
              			
              	    	intent.putExtra("IdAviso", idAviso);
              	    	intent.putExtra("_IdAviso", _idAviso);
              	    	intent.putExtra("posicion", position );
              	    	//intent.putExtra("bandera", 1);
              	    	startActivityForResult(intent, SECONDARY_ACTIVITY_REQUEST_CODE);*/
              	    	//startActivity(intent);
              	}
              	});
              	
             }
            
           
             //avisosTable.close();
        }
        catch (Exception ex)
        {
            logger.debug(CLASS_NAME + " - LoadLista");
            logger.debug(FunctionsUtil.getExceptionInfoToLog(ex));
            FunctionsUtil.ShowMessage("Error: " + ex.getMessage(),Toast.LENGTH_LONG);
        }
        //Miguel Para evitar la excepcion, es mejor usar dismiss en lugar de hide
        //http://stackoverflow.com/questions/2850573/activity-has-leaked-window-that-was-originally-added
        //progressDialog.hide();
        progressDialog.dismiss();
    }
	
	
	
	protected SimpleCursorAdapter obtenAdaptador(Cursor c) {
		return new SimpleCursorAdapter(this,
               R.layout.listavisos,
               c, // Give the cursor to the list adapter
               new String[] {EJEMPLARTABLE.KEY_NOMBRE,EJEMPLARTABLE.KEY_RAZA,"GENERO", 
				
				"ESPECIE"
				//"NombreContradto"
				}, // Map the column in the
               new int[] {R.id.lblLaCodigo, R.id.lblLaCentro , R.id.lblLaEspecie , R.id.lblLaDescripgenerotexto}); // The view defined in the XML template
	}
	
	
	
	
	//we need a handler for when the secondary activity finishes it's work
    //and returns control to this activity...
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    	try{
	        super.onActivityResult(requestCode, resultCode, intent);
        	Context context = getApplicationContext();
        	
        	
        	
        	
            Toast toast = Toast.makeText(context, "Listando avisos nuevamente...",Toast.LENGTH_LONG);
            toast.show();
        	
            try {
            	  int index=intent.getIntExtra("index",-1);
              	int top=intent.getIntExtra("top",-1);
              			
                  
      	        LoadLista();
      	        
      	    	if (index!=-1) empListView.setSelectionFromTop(index, top);
			} catch (Exception e) {
				 LoadLista();
				// TODO: handle exception
			}
            
          
	    	
	        estableceTitulos();
	    	position = getIntent().getIntExtra("position",0);
    	}
    	catch(Exception ex){
    		logger.debug(CLASS_NAME + " - onActivityResult");
            logger.debug(FunctionsUtil.getExceptionInfoToLog(ex));
            FunctionsUtil.ShowMessage("Error: " + ex.getMessage(),Toast.LENGTH_LONG);
    	}
    }
    
    
    //nuevo GCR
    
   
    
    
    
    
    


}
